﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;

namespace Administracion.Administracion
{
    public class ClsXml
    {
        public string NombreArchivo { get; set; }
        public string ElementoInicial { get; set; }
        public string Elemento { get; set; }
        public void GenerarArchivo(DataTable dt)
        {
            var sw = new StreamWriter(NombreArchivo, false);
            var sxml = new XmlTextWriter(sw);
            sxml.Indentation = 4;
            sxml.WriteStartDocument(true);
            sxml.WriteStartElement(ElementoInicial);
            DataColumnCollection dts = dt.Columns;
            foreach (DataRow dr in dt.Rows)
            {
                CrearElemento(sxml, dts, dr, Elemento);
            }
            sxml.WriteEndElement();
            sxml.WriteEndDocument();
            sxml.Flush();
            sxml.Close();

        }
        private static void CrearElemento(XmlTextWriter sxml, DataColumnCollection dts, DataRow dr, string element)
        {
            sxml.WriteStartElement(element);
            foreach (DataColumn dc in dts)
            {
               sxml.WriteAttributeString(dc.ColumnName, dr[dc.ColumnName].ToString());
            }
            sxml.WriteEndElement();
        }

        public XmlDocument GenerarXml(DataTable dt)
        {
            var xDoc = new XmlDocument();
            xDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            XmlNode xmlnode = xDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            xDoc.AppendChild(xmlnode);
            XmlElement xmlelem = xDoc.CreateElement("", ElementoInicial, "");
            xDoc.AppendChild(xmlelem);

            DataColumnCollection dts = dt.Columns;
            foreach (DataRow dr in dt.Rows)
            {
                XmlElement xmlelem2 = xDoc.CreateElement("", Elemento, "");
                ElementoXml(xDoc, dts, dr, xmlelem2);
                xDoc.ChildNodes.Item(1).AppendChild(xmlelem2);
            }

            return xDoc;
        }
        private static XmlElement ElementoXml(XmlDocument xDoc, DataColumnCollection dts, DataRow dr, XmlElement element)
        {
            foreach (DataColumn dc in dts)
            {

               
                    
              
                    element.SetAttribute(dc.ColumnName, dr[dc.ColumnName].ToString());
                

            }
            return element;
        }
    }
}
